<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Wechat extends Controller{
//+-----------------------------------------------------------------------
    //配置微信平台URL
    public function weixinURL(){
        $whereAB['wx_original_id']=input('get.yanzheng');
        $wechatRes=Db::name('wechatconfig')->where($whereAB)->find();

        //将timestamp，nonce，token按字典排序
        $timestamp =input('get.timestamp');
        $nonce     =input('get.nonce');
        $echostr   =input('get.echostr');
        $token     =md5($wechatRes['wx_original_id']);
        $signature =input('get.signature');
        $array     =array($timestamp,$nonce,$token);
        sort($array);
        //将排序后的三个参数拼接之后用sha1加密
        $tmpstr=sha1(implode($array));

        //dump(md5(md5($wechatRes['wx_original_id'])));exit();
        //将加密后的字符串与signature进行对比，判断该请求是否来自微信
        if($tmpstr==$signature && $echostr){
            echo $echostr;
            exit();
        }else{
            $this->reponseMsg();
        }
    }
    //关注时回复
    public function reponseMsg(){
        $whereAB['re_id']=1;
        $reponRes=Db::name('reponsemsg')->where($whereAB)->find();
//        file_put_contents("../wx.txt",2222, FILE_APPEND);
        //1.获取微信推送过来的post数据（xml格式）
        $postArr=file_get_contents("php://input");
//        file_put_contents("../wx.txt",$postArr, FILE_APPEND);

        //2.处理消息类型，并设置回复类型和内容
        $postObj=simplexml_load_string($postArr);

        //关注时添加会员
        $data['openid']=$postObj->FromUserName;
        $whereAC['openid']=$postObj->FromUserName;


        //判断该数据包是否是订阅的事件推送
        //关注时回复
        if(strtolower($postObj->MsgType=='event')){
            //如果是关注subscribe事件
            if(strtolower($postObj->Event=='subscribe')){
                $data['openid']=$postObj->FromUserName;
                $whereAC['openid']=$postObj->FromUserName;
                $useropenid = Db::name('member')->where($whereAC)->find();
                if(empty($useropenid)){
                    $data['create_time']=time();
                    Db::name('member')->insert($data);
                }else{
                    Db::name('member')->where($whereAC)->update($data);
                }
                if($reponRes['re_state']==1){
                    //回复用户图文消息
                    $toUser=$postObj->FromUserName;
                    $fromUser=$postObj->ToUserName;
                    $time=time();
                    $msgType='text';

                    $urlaa='http://'.$_SERVER['HTTP_HOST'];
                    $content=array(
                        array(
                            'title'=>$reponRes['re_title'],
                            'description'=>$reponRes['re_remark'],
                            'picUrl'=>$urlaa.'/'.$reponRes['re_image'],
                            'url'=>$reponRes['re_url'],
                        ),
                    );
                    $template="<xml>
	                            <ToUserName><![CDATA[%s]]></ToUserName>
	                            <FromUserName><![CDATA[%s]]></FromUserName>
	                            <CreateTime>%s</CreateTime>
	                            <MsgType><![CDATA[%s]]></MsgType>
	                            <ArticleCount>1</ArticleCount>
	                            <Articles>";
                    foreach ($content as $k=>$v) {
                        $template.="<item>
	                                <Title><![CDATA[".$v['title']."]]></Title>
	                                <Description><![CDATA[".$v['description']."]]></Description>
	                                <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
	                                <Url><![CDATA[".$v['url']."]]></Url>
	                                </item>";
                    }
                    $template.="</Articles>
	                            </xml>";
                    echo sprintf($template,$toUser,$fromUser,$time,'news');
                }else{
                    //回复文字消息
                    $toUser=$postObj->FromUserName;
                    $fromUser=$postObj->ToUserName;
                    $time=time();
                    $msgType='text';
                    $content=$reponRes['re_remark'];

                    $template="
										<xml>
										<ToUserName><![CDATA[%s]]></ToUserName>
										<FromUserName><![CDATA[%s]]></FromUserName>
										<CreateTime>%s</CreateTime>
										<MsgType><![CDATA[%s]]></MsgType>
										<Content><![CDATA[%s]]></Content>
										</xml>
								";
                    $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
                    echo $info;
                }
            }
            if(strtolower($postObj->Event=='unsubscribe')){
            }
            //点击回复图文
            elseif(strtolower($postObj->Event)=='click'){
                if($postObj->EventKey==$postObj->EventKey){
                    $titleaa=$postObj->EventKey;
                    $whereaa['t_explain']=strtolower($titleaa);
                    $result=Db::name('imgtext')->where($whereaa)->find();
                    $fromUser=$postObj->ToUserName;
                    $toUser=$postObj->FromUserName;
                    $time=time();

                    $url='http://'.$_SERVER['HTTP_HOST'];
                    if($result['t_explain']==$postObj->EventKey){
                        if($result['t_url']==""){
                            $arr=array(
                                array(
                                    'title'=>$result['t_title'],
                                    'description'=>$result['t_synopsis'],
                                    'picUrl'=>$url.'/'.$result['t_img'],
                                    'url'=>$url.'/index/index/imgtext?id='.$result['id'],
                                ),
                            );
                        }else{
                            $arr=array(
                                array(
                                    'title'=>$result['t_title'],
                                    'description'=>$result['t_synopsis'],
                                    'picUrl'=>$url.$result['t_img'],
                                    'url'=>$result['t_url'],
                                ),
                            );
                        }

                        $template="<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount>1</ArticleCount>
                                <Articles>";
                        foreach ($arr as $k=>$v) {
                            $template.="<item>
                                    <Title><![CDATA[".$v['title']."]]></Title>
                                    <Description><![CDATA[".$v['description']."]]></Description>
                                    <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
                                    <Url><![CDATA[".$v['url']."]]></Url>
                                    </item>";
                        }
                        $template.="</Articles>
                                </xml>";
                        echo sprintf($template,$toUser,$fromUser,$time,'news');
                    }else{
                        $toUser=$postObj->FromUserName;
                        $fromUser=$postObj->ToUserName;
                        $time=time();
                        $msgType='text';
                        $content='没有设置回复';

                        $template="
                        <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        </xml>
                    ";
                        $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
                        echo $info;
                    }

                }
            }
            elseif(strtolower($postObj->Event=='SCAN')){
                $data['openid']=$postObj->FromUserName;
                $whereAC['openid']=$postObj->FromUserName;
                $useropenid = Db::name('member')->where($whereAC)->find();
                if(empty($useropenid)){
                    $data['create_time']=time();
                    Db::name('member')->insert($data);
                }
                if($reponRes['re_state']==0){
                    //回复用户图文消息
                    $toUser=$postObj->FromUserName;
                    $fromUser=$postObj->ToUserName;
                    $time=time();
                    $msgType='text';

                    $urlaa='http://'.$_SERVER['HTTP_HOST'];
                    $content=array(
                        array(
                            'title'=>$reponRes['re_title'],
                            'description'=>$reponRes['re_remark'],
                            'picUrl'=>$urlaa.'/'.$reponRes['re_image'],
                            'url'=>$reponRes['re_url'],
                        ),
                    );
                    $template="<xml>
															<ToUserName><![CDATA[%s]]></ToUserName>
															<FromUserName><![CDATA[%s]]></FromUserName>
															<CreateTime>%s</CreateTime>
															<MsgType><![CDATA[%s]]></MsgType>
															<ArticleCount>1</ArticleCount>
															<Articles>";
                    foreach ($content as $k=>$v) {
                        $template.="<item>
																	<Title><![CDATA[".$v['title']."]]></Title>
																	<Description><![CDATA[".$v['description']."]]></Description>
																	<PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
																	<Url><![CDATA[".$v['url']."]]></Url>
																	</item>";
                    }
                    $template.="</Articles>
															</xml>";
                    echo sprintf($template,$toUser,$fromUser,$time,'news');
                }else{
                    //回复文字消息
                    $toUser=$postObj->FromUserName;
                    $fromUser=$postObj->ToUserName;
                    $time=time();
                    $msgType='text';
                    $content='没有设置回复';

                    $template="
										<xml>
										<ToUserName><![CDATA[%s]]></ToUserName>
										<FromUserName><![CDATA[%s]]></FromUserName>
										<CreateTime>%s</CreateTime>
										<MsgType><![CDATA[%s]]></MsgType>
										<Content><![CDATA[%s]]></Content>
										</xml>
								";
                    $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
                    echo $info;
                }
            }else{
                //回复文字消息
                $toUser=$postObj->FromUserName;
                $fromUser=$postObj->ToUserName;
                $time=time();
                $msgType='text';
                $content='没有设置回复！';

                $template="
										<xml>
										<ToUserName><![CDATA[%s]]></ToUserName>
										<FromUserName><![CDATA[%s]]></FromUserName>
										<CreateTime>%s</CreateTime>
										<MsgType><![CDATA[%s]]></MsgType>
										<Content><![CDATA[%s]]></Content>
										</xml>
								";
                $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
                echo $info;
            }
        }
    }
    //获取access_token
    public function getWxAccessToken(){
        //将access_token存在session/cookie中

        if(session('access_token')&&session('expire_time')>time()){
            //如果access_token在session并没有过期
            return session('access_token');

        }
        else{
            $whereAB['wx_id']=1;
            $wechatRes=Db::name('wechatconfig')->where($whereAB)->find();

            $appid=$wechatRes['appid'];
            $appsecret=$wechatRes['appsecret'];

            //如果access_token不存在或者session已经过期，重新获取access_token
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
            $res=$this->http_curl($url,'get','json');

            $access_token=$res['access_token'];
            //将重新获取到的access_token存到session中
            session('access_token',$access_token);
            $time=time()+7200-500;
            session('expire_time',$time);
            return $access_token;
        }
    }


    protected function http_curl($url,$type='get',$res='json',$arr=''){
        //1、初始化curl
        $ch=curl_init();
        //2、设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if($type=='post'){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3、采集
        $output=curl_exec($ch);
        //4、关闭

        if($res=='json'){
            return json_decode($output,true);
        }
        curl_close($ch);
    }
    /*
     * 生成微信菜单
     */
    public function pub_menu(){
        $menu = array();
        $menu['button'][] = array(
            'name'=>'测试',
            'type'=>'view',
            'url'=>'http://www.tp-shop.cn'
        );
        $menu['button'][] = array(
            'name'=>'测试',
            'sub_button'=>array(
                array(
                    "type"=> "scancode_waitmsg",
                    "name"=> "系统拍照发图",
                    "key"=> "rselfmenu_1_0",
                    "sub_button"=> array()
                )
            )
        );

        //获取父级菜单
        $p_menus = Db::name('menu')->where(array('menu_id'=>0))->limit(3)->order('menu_sort asc')->select();

        $post_str = $this->convert_menu($p_menus);


        if(!count($p_menus) > 0){
            return json(array('code'=>'error','msg'=>'没有菜单可发布!'));
        }
        $access_token = $this->getWxAccessToken();

        if(!$access_token){
            return json(array('code'=>'error','msg'=>'获取access_token失败'));
        }
        $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        $return = $this->http_curl($url,'post','json',$post_str);

        if($return['errcode'] == 0){
            return json(array('code'=>'success'));
        }else{
            return json(array('code'=>'error','msg'=>$return['errcode']));
        }
    }

    //菜单转换
    public function convert_menu($p_menus){
        $key_map = array(
            'scancode_waitmsg'=>'rselfmenu_0_0',
            'scancode_push'=>'rselfmenu_0_1',
            'pic_sysphoto'=>'rselfmenu_1_0',
            'pic_photo_or_album'=>'rselfmenu_1_1',
            'pic_weixin'=>'rselfmenu_1_2',
            'location_select'=>'rselfmenu_2_0',
        );
        $new_arr = array();
        $count = 0;
        foreach($p_menus as $k => $v){
            $new_arr[$count]['name'] = $v['menu_name'];

            //获取子菜单
            $c_menus = Db::name('menu')->where(array('menu_id'=>$v['id']))->order('menu_sort asc')->select();

            if($c_menus){
                foreach($c_menus as $kk=>$vv){
                    $add = array();
                    $add['name'] = $vv['menu_name'];
                    $add['type'] = $vv['menu_type'];
                    // click类型
                    if($add['type'] == 'click'){
                        $add['key'] = $vv['menu_typecontent'];
                    }elseif($add['type'] == 'view'){
                        $add['url'] = $vv['menu_typecontent'];
                    }else{
                        //$add['key'] = $key_map[$add['type']];
                        $add['key'] = $vv['menu_typecontent'];
                    }
                    $add['sub_button'] = array();
                    if($add['name']){
                        $new_arr[$count]['sub_button'][] = $add;
                    }
                }
            }else{
                $new_arr[$count]['type'] = $v['menu_type'];
                // click类型
                if($new_arr[$count]['type'] == 'click'){
                    $new_arr[$count]['key'] = $v['menu_typecontent'];
                }elseif($new_arr[$count]['type'] == 'view'){
                    //跳转URL类型
                    $new_arr[$count]['url'] = $v['menu_typecontent'];
                }else{
                    //其他事件类型
                    $new_arr[$count]['key'] = $v['menu_typecontent'];  //2016年9月29日01:40:13
                }
            }
            $count++;
        }
        // return json_encode(array('button'=>$new_arr));
        return json_encode(array('button'=>$new_arr),JSON_UNESCAPED_UNICODE);
    }
}